package com.wowoai.user.repository.impl;

import com.github.wenhao.jpa.PredicateBuilder;
import com.github.wenhao.jpa.Specifications;
import com.wowoai.common.basemodule.BusinessException;
import com.wowoai.common.reponsitory.DataJpaBaseDao;
import com.wowoai.user.entity.UserEntity;
import com.wowoai.user.repository.UserRepositoryI;
import com.wowoai.user.repository.jpa.UserJpaRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 持久化层 DataJpaBaseDao中实现了UserRepositoryI 中的基本接口
 */
@Repository
public class UserRepositoryImpl extends DataJpaBaseDao<UserEntity,Long> implements UserRepositoryI {

    private final UserJpaRepository userJpaRepository;

    public UserRepositoryImpl(UserJpaRepository dataJpaRepository) {
        super(dataJpaRepository);
        userJpaRepository = dataJpaRepository;
    }
    @Override
    public UserEntity findByPhoneNumber(String phoneNumber) {
        PredicateBuilder<UserEntity> builder = Specifications.and();

        builder.eq("phoneNumber",phoneNumber);
        builder.eq("deleted",Boolean.FALSE);
        return userJpaRepository.findOne(builder.build()).orElse(null);
    }

    @Override
    public UserEntity findById(Long userId) {
        PredicateBuilder<UserEntity> builder = Specifications.and();
        builder.eq("id",userId);
        builder.eq("deleted",Boolean.FALSE);
        return userJpaRepository.findOne(builder.build()).orElseThrow(() -> new BusinessException("查询的用户不存在"));
    }

    @Override
    public List<UserEntity> findAll() {
        PredicateBuilder<UserEntity> builder = Specifications.and();
        builder.eq("deleted",Boolean.FALSE);
        return userJpaRepository.findAll(builder.build());
    }
}
